package com.molihub.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.molihub.component.MyWebSocketHandler;
import com.molihub.entity.*;
import com.molihub.utils.LogUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * @ClassName: FriendController
 * @Description: 处理好友添加，关注等控制器
 * @author: GGBOY
 * @date 2020/1/31 17:02
 * @Version: 1.0
 **/
@Controller
public class FriendController extends BaseController {

    private Logger logger = LogUtils.getInstance(FriendController.class);

    /**
     * 接收好友请求
     *
     * @param userName       申请人用户名
     * @param followUserName 被添加人用户名
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/1/31
     */
    @ResponseBody
    @GetMapping("/friend/accept/{userName}/{followUserName}")
    public String accept(@PathVariable String userName, @PathVariable String followUserName) {
        logger.info("同意添加好友请求：" + userName + " --> " + followUserName);
        // 申请人
        User userApplicant = userService.getUserByUserName(userName);
        // 被添加人
        User userHandler = userService.getUserByUserName(followUserName);
        // 封装成Friend实体
        Friend my = Friend.builder()
                .friendId(userHandler.getUserId())
                .userId(userApplicant.getUserId())
                .time(new Date())
                .build();
        Friend friend = Friend.builder()
                .friendId(userApplicant.getUserId())
                .userId(userHandler.getUserId())
                .time(new Date())
                .build();
        // 封装 UserFollow实体类，关注
        UserFollow userFollow = UserFollow.builder()
                .userId(userApplicant.getUserId())
                .followUserId(userHandler.getUserId())
                .time(new Date()).build();
        UserFollow userFollow1 = UserFollow.builder()
                .userId(userHandler.getUserId())
                .followUserId(userApplicant.getUserId())
                .time(new Date()).build();
        userFollowService.addRecord(userFollow);
        userFollowService.addRecord(userFollow1);
        // 封装Message实体
        Message message1 = Message.builder()
                .messageTime(new Date()).fromUserId(userApplicant.getUserId())
                .toUserId(userHandler.getUserId())
                .followId(userFollow.getFollowId())
                .isLooked(0).build();
        Message message2 = Message.builder()
                .messageTime(new Date()).fromUserId(userHandler.getUserId())
                .toUserId(userApplicant.getUserId())
                .followId(userFollow1.getFollowId())
                .isLooked(0).build();
        // 向Message表添加双向关注的消息
        messageService.addRecord(message1);
        messageService.addRecord(message2);
        // 执行添加操作
        friendService.addRecord(my);
        friendService.addRecord(friend);
        // 通知对方，同意了好友请求
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("A", userHandler.getUserName());
        jsonObject.put("B", userApplicant.getUserName());
        jsonObject.put("content", "接收了你的请求。");
        // flag位为2表示同意添加好友请求
        jsonObject.put("flag", "2");
        // 将双方用户的详细信息也添加到消息内容中去
        jsonObject.put("aUserInfo", userHandler);
        jsonObject.put("bUserInfo", userApplicant);

        // 将对应的好友添加请求状态更新为已接收
        List<RequestMessage> messageByIdAndFlag =
                requestMessageService.findMessageByIdAndFlag(userApplicant.getUserId(),
                        userHandler.getUserId(), 1);
        if (messageByIdAndFlag.size() != 0) {
            for (RequestMessage requestMessage : messageByIdAndFlag) {
                requestMessage.setIsReceive(1);
                requestMessageService.updateMessage(requestMessage);
            }
        }
        // 将同意好友添加请求记录在数据库中，
        RequestMessage message = RequestMessage.builder()
                .aUserId(userHandler.getUserId()).bUserId(userApplicant.getUserId()).build();
        message.setMessageContent(jsonObject.toJSONString());
        message.setFlag(2);
        requestMessageService.addMessage(message);
        // 发送消息给对方，通知其添加好友成功
        MyWebSocketHandler.aSendMessageToB(userHandler.getUserId(), userApplicant.getUserId(),
                jsonObject.toJSONString());
        return "OK";
    }

    /**
     * 拒绝添加好友请求
     *
     * @param userName       发起添加好友请求的用户
     * @param followUserName 拒绝添加好友请求的用户
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/1/31
     */
    @ResponseBody
    @GetMapping("/friend/refuse/{userName}/{followUserName}")
    public String refuseRequest(@PathVariable String userName, @PathVariable String followUserName) {
        User bUser = userService.getUserByUserName(userName);
        User aUser = userService.getUserByUserName(followUserName);
        // 构建一个JSON对象，发送JSON信息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("A", aUser.getUserName());
        jsonObject.put("B", bUser.getUserName());
        jsonObject.put("content", "拒绝了您的请求。");
        // flag位为3表示拒绝添加好友请求
        jsonObject.put("flag", "3");

        // 将双方用户的详细信息也添加到消息内容中去
        jsonObject.put("aUserInfo", aUser);
        jsonObject.put("bUserInfo", bUser);
        logger.info("拒绝添加: " + jsonObject.toJSONString());
        // 将对应的好友添加请求状态更新为已接收
        List<RequestMessage> messageByIdAndFlag = requestMessageService.findMessageByIdAndFlag(bUser.getUserId(),
                aUser.getUserId(), 1);
        if (messageByIdAndFlag.size() != 0 && messageByIdAndFlag != null) {
            for (RequestMessage requestMessage : messageByIdAndFlag) {
                requestMessage.setIsReceive(1);
                requestMessageService.updateMessage(requestMessage);
            }
        }
        // 将同意好友添加请求记录在数据库中，
        RequestMessage message = RequestMessage.builder()
                .aUserId(aUser.getUserId()).bUserId(bUser.getUserId()).build();
        message.setMessageContent(jsonObject.toJSONString());
        message.setFlag(3);
        requestMessageService.addMessage(message);
        // 发送消息给对方，通知其添加好友失败
        MyWebSocketHandler.aSendMessageToB(aUser.getUserId(), bUser.getUserId(), jsonObject.toJSONString());
        return "OK";
    }


    /**
     * 查找双方用户是否存在关系
     *
     * @param followUserName 用户名
     * @param userName       用户名
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/2
     */
    @ResponseBody
    @GetMapping("/isFriend/{userName}/{followUserName}")
    public String findRecordById(@PathVariable String followUserName, @PathVariable String userName) {
        logger.info("findRecordById........ " + followUserName + " " + userName);
        User user = userService.getUserByUserName(userName);
        User followUser = userService.getUserByUserName(followUserName);
        // 查找用户之间是否存在关系
        Friend recordById = friendService.findRecordById(user.getUserId(), followUser.getUserId());
        Friend recordById1 = friendService.findRecordById(followUser.getUserId(), user.getUserId());
        if (recordById != null || recordById1 != null) {
            // 表示存在关系
            return "YES";
        } else {
            // 表示不存在关系
            return "NO";
        }
    }

    /**
     * 查找用户的所有好友
     *
     * @param userName 用户名
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/3
     */
    @ResponseBody
    @GetMapping("/friend/findAll/{userName}")
    public String findAllFriend(@PathVariable String userName) {
        logger.info("findAllFriend----->: " + userName);
        User user = userService.getUserByUserName(userName);
        List<User> friends = friendService.findAllFriendById(user.getUserId());
        notifyFriends(user, friends);
        return JSON.toJSONString(friends);
    }

    /**
     * 通知好友，用户状态改变了
     *
     * @param user    当前改变状态用户
     * @param friends 用户的好友
     * @return void
     * @author GGBOY
     * @date 2020/2/7
     */
    public static void notifyFriends(User user, List<User> friends) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("A", user.getUserName());
        for (User friend :
                friends) {
            jsonObject.put("B", friend.getUserName());
            jsonObject.put("flag", "5");
            jsonObject.put("aUserInfo", user);
            jsonObject.put("bUserInfo", friend);
            // 通知好友，我上线了
            MyWebSocketHandler.aSendMessageToB(user.getUserId(), friend.getUserId(), jsonObject.toJSONString());
        }
    }
}
